package com.lele.SpringSecurity.utils;

import com.lele.SpringSecurity.domain.Permission;
import com.lele.SpringSecurity.domain.User;
import com.lele.SpringSecurity.service.PermissionService;
import com.lele.SpringSecurity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class AdminUserDetailsService implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userService.getUserByUsername(username);
        // 不加密
        user.setPassword("{noop}" + user.getPassword());
        // 添加权限
        List<Permission> permissions = permissionService.getPermissionByUsername(username);
        for (Permission permission: permissions) {
            String permTag = permission.getPermTag();

            Set<GrantedAuthority> grantedAuthorities = new HashSet<>();

            grantedAuthorities.add(new SimpleGrantedAuthority(permTag));

            user.setAuthorities(grantedAuthorities);
        }
        return user;
    }
}
